
var UrlParam = function() { // url参数
  var data, index;    
  (function init() {    
    data = [];    //值，如[["1","2"],["zhangsan"],["lisi"]]
    index = {};   //键:索引，如{a:0,b:1,c:2}
    var u = window.location.search.substr(1);    
    if (u != '') {    
      var params = decodeURIComponent(u).split('&');
      for (var i = 0, len = params.length; i < len; i++) {
        if (params[i] != '') {
          var p = params[i].split("=");
          if (p.length == 1 || (p.length == 2 && p[1] == '')) {// p | p= | =
            data.push(['']);    
            index[p[0]] = data.length - 1;    
          } else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c 舍弃

            continue;

          } else if (typeof(index[p[0]]) == 'undefined') { // c=aaa    

            data.push([p[1]]);    

            index[p[0]] = data.length - 1;    
          } else {// c=aaa    
            data[index[p[0]]].push(p[1]);    
          }    
        }    
      }    
    }    
  })();    
  return {    
    param : function(o) { // o: 参数名或者参数次序
      try {    
        return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);    
      } catch (e) {    
      }    
    },    
    //获得参数组, 类似request.getParameterValues()    
    paramValues : function(o) { //  o: 参数名或者参数次序
      try {    
        return (typeof(o) == 'number' ? data[o] : data[index[o]]);    
      } catch (e) {}    
    },    
    //是否含有paramName参数
    hasParam : function(paramName) {
      return typeof(paramName) == 'string' ? typeof(index[paramName]) != 'undefined' : false;
    },    
    // 获得参数Map ,类似request.getParameterMap()    
    paramMap : function() {
      var map = {};    
      try {    
        for (var p in index) {  map[p] = data[index[p]];  }    
      } catch (e) {}    
      return map;    
    }    
  }    
}();

var categories = [] //产品类别
var insuranceCategory = [] //险种类别
var types = [] //发布栏目
var permissionses = [] //可查看人员
var organs = [] //可查看机构
var productFilesTypes = [] //产品属性附件类别
var activityFilesTypes = [] //项目/活动附件类别
var saleFilesTypes = [] //销售计划附件类别
var products = [] //使用产品
var channels = [] //使用渠道
var productState = []//产品状态
var relaseState = []//发布状态

new Vue({
    el: '#product',
    data: function () {
        return {
            categories: categories,
            types: types,
            permissionses: permissionses,
            organs: organs,
            filesTypes: productFilesTypes,
            ruleForm: {
                id: '',
                productname: '',
                productcode: '',
                insurancetype: '',
                productstate: '在售',
                releasestate: '有效',
                relaseDate: '',
                ident: '0',
                releasecolumns: [],
                usechannels: [],
                viewablepsns: [],
                viewabledepts: ['分公司'],
                files: [
                    { filesTypes: '产品条款', fileList:[]},
                    { filesTypes: '产品说明书', fileList:[]},
                    { filesTypes: '费率表', fileList:[]},
                    { filesTypes: '投保规则', fileList:[]},
                    { filesTypes: '保全规则', fileList:[]},
                    { filesTypes: '产品彩页', fileList:[]},
                    { filesTypes: '营运资料', fileList:[]},
                    { filesTypes: '产品佣金率', fileList:[]}
                ]
            },
            productrules: {
	           /* productcode: [
	                {required: true, message: '请输入产品代码', trigger: 'blur'},
	                {min: 1, max: 10, message: '请输入长度在 1 到 10 的字符', trigger: 'blur' }
	            ],*/
	            productname: [
	                {required: true, message: '请输入产品名称', trigger: 'blur'}
	            ],
	            insurancetype: [
	          	    {required: true, message: '请选择险种类别', trigger: 'change'}
	            ],
	            productstate: [
	                {required: true, message: '请选择产品状态', trigger: 'change'}
	            ],
	            releasestate: [
	                {required: true, message: '请选择发布状态', trigger: 'change'}
	            ],
	            viewabledepts: [
	        	    {required: true, message: '请选择可查看机构', trigger: 'change'}
	            ]
            },
            fileList: [],
            idx: 0
            
        }
    },
    created: function () {
    	var parameter = window.location.search
    	if(parameter != null && parameter !=""){
    		document.getElementById("button3").textContent="返回";
    	}
    	this.loadOption()
    },
    methods: {
    	uploadFile: function(index){
    		return "/product/uploadFile/"+index;
    	},
        handlePreview: function () {
            // 点击已上传的文件链接时的钩子，可以通过file.response拿到服务端返回数据
        },
        handleRemove: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	var index = file.index;
        	this.ruleForm.files[index].fileList=fileList;
        },
        beforeRemove: function (file, fileList) {
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回false或者返回Promise且被reject，则停止上传。
        	return this.$confirm('确定移除' + file.name)
        },
     // 上传成功后的回调
        uploadSuccess: function(response, file, fileList) {
        	var att = response.data;
        	this.idx = response.data.index;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.ruleForm.files[this.idx].fileList=fileList;
    
          console.log('上传文件', response)
        },
        // 上传错误
        uploadError: function(response, file, fileList) {
          console.log('上传失败，请重试！')
        },

        handleExceed: function (file, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning('当前限制选择10个文件，本次选择了' + file.length + '个文件，共选择了' + Number(file.length +fileList.length) + '个文件')
        },
        closeDialog: function (formName) { //关闭清除校验结果
            this.$refs[formName].clearValidate()
        },
        addAccessory: function () { //增加附件
            this.ruleForm.files.push({
                filesTypes: '',
                fileList:[]
            })
        },
        removeAccessory: function (item) { //删除附件
            var index = this.ruleForm.files.indexOf(item)
            if (index !== -1) {
                this.ruleForm.files.splice(index, 1);
//                this.attList.splice(index, 1);
            }
        },
        resetForm: function (formName,upload,update) { //清空or返回
        	if(document.getElementById("button3").textContent=="返回"){
        		window.location.href = './productItems?update=' + update + '#product'
        	}else{
	            this.$refs[formName].resetFields()
	            var uploads = this.$refs.upload;
	            for(var i = 0; i < uploads.length; i++){
	            	uploads[i].clearFiles();
	            }
        	}
        },
        submitForm: function () { //确认发布
        	var _this=this;
        	this.$refs['ruleForm'].validate(function (valid) {
                if (valid) {
		        	$.ajax({
		                url: '/product/saveOrupdateProduct',
		                data: {"data":JSON.stringify(_this.ruleForm)},
		                type: 'post',
		                dataType: 'json',
		                success: function (res) {
		                	var update = '';
		                	if(document.getElementById("button3").textContent=="清空"){
			                    _this.$alert('','保存成功', {
			                        confirmButtonText: '确定',
			                        type:'success',
			                        center:'true'
			                    });
		                	}else{
		                		update = 1;
		                	}
			                    _this.resetForm('ruleForm','upload',update);
			                    sale.loadOption();
		                },
		                error: function (err) {
		                	if(err.responseJSON.message=="session clean"){
		                        errorMessage(_this.$message, '登陆已失效重新登陆!');
		                        toLogin();
		                        return;
		                    }
                            if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
		                	_this.$alert('','发布失败，请检查参数或文件是否为空！', {
		                        confirmButtonText: '确定',
			                	type:'error',
			                	center:'true'
			            	});
		                }
		            });
                }
        	});
        },
        /*
         * 页面初始化,加载下拉选项
         * */
        loadOption: function (){
        	var _this = this;
            $.ajax({
                url: '/product/loadOption',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                   _this.insuranceCategory = res.data.projectInsuranceCategory;//险种类别
                   _this.productState = res.data.productState;//产品状态
                   _this.relaseState = res.data.releaseState;//发布状态
                   _this.types = res.data.releaseColumn;//发布栏目
                   _this.channels = res.data.useChannels//使用渠道
                   _this.productFilesTypes = res.data.productEnclosureCategory;//产品属性附件类别
                   _this.organs = res.data.postOrganization;//可查看岗机构
                   _this.permissionses = res.data.TP_NAME;//可查看岗位
                },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                	errorMessage(_this.$message, '初始化下拉列表出错！')
                }
            })
          /*//获取id
            var request = {
	       			QueryString : function(val) {
	       			var uri = window.location.search;
	       			var re = new RegExp("" +val+ "=([^&?]*)", "ig");
	       			return ((uri.match(re))?(uri.match(re)[0].substr(val.length+1)):null);
	       			},
	       			hash : window.location.hash
	        }*/
        	var id=UrlParam.param("id");
            var type=UrlParam.param("type");
        	if(id!=null&&id!=""&&type.indexOf("product")!=-1){
        	//通过id查询对应产品信息
	        	 $.ajax({
	                 url: '/product/findProductbyId',
	                 data: {"id":id},
	                 type: 'post',
	                 dataType: 'json',
	                 success: function (res) {
	                    _this.ruleForm = res.data;//险种类别
	                 },
	                 error: function (err) {
	                	 if(err.responseJSON.message=="session clean"){
	                         errorMessage(_this.$message, '登陆已失效重新登陆!');
	                         toLogin();
	                         return;
	                     }
	                 	errorMessage(_this.$message, '')
	                 }
	             })
        	}
        }
    }
})

new Vue({
    el: '#activity',
    data: function () {
        return {
            ruleForm: {
            	projectname: '',
            	relaseDate: '',
                releasestate: '有效',
                files: [
						{ filesTypes: '折页', fileList:[]},
						{ filesTypes: '海报', fileList:[]},
						{ filesTypes: '宣传H5', fileList:[]},
						{ filesTypes: '宣传视频', fileList:[]}
                    ]
                },
                rules: {
                	  projectname: [
	                      {required: true, message: '请输入项目活动名称', trigger: 'blur'}
	                  ],
	                  releasestate: [
	                      {required: true, message: '请选择发布状态', trigger: 'change'}
	                  ]
                },
                fileList: [],
                idx: 0,
            types: types,
            categories: [],
            activityFilesTypes: [],
            fileList: [],
            relaseState:[]
        }
    },
    created: function () {
    	var parameter = window.location.search
    	if(parameter != null && parameter !=""){
    		document.getElementById("button2").textContent="返回";
    	}
    	this.loadOption()
    },
    methods: {
    	uploadFile: function(index){
    		return "/product/uploadFile/"+index;
    	},
        handlePreview: function () {
            // 点击已上传的文件链接时的钩子，可以通过file.response拿到服务端返回数据
        },
        handleRemove: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	var index = file.index;
        	this.ruleForm.files[index].fileList=fileList;
        },
        beforeRemove: function (file, fileList) {
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回false或者返回Promise且被reject，则停止上传。
        	return this.$confirm('确定移除' + file.name)
        },
     // 上传成功后的回调
        uploadSuccess: function(response, file, fileList) {
        	var att = response.data;
        	this.idx = response.data.index;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.ruleForm.files[this.idx].fileList=fileList;
    
          console.log('上传文件', response)
        },
        // 上传错误
        uploadError: function(response, file, fileList) {
          console.log('上传失败，请重试！')
        },

        handleExceed: function (file, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning('当前限制选择10个文件，本次选择了' + file.length + '个文件，共选择了' + Number(file.length +fileList.length) + '个文件')
        },
        addAccessory: function () { //增加附件
            this.ruleForm.files.push({
                filesTypes: '',
                fileList:[]
            })
        },
        removeAccessory: function (item) { //删除附件
            var index = this.ruleForm.files.indexOf(item)
            if (index !== -1) {
                this.ruleForm.files.splice(index, 1);
//                this.attList.splice(index, 1);
            }
        },
        resetForm: function (formName,upload,update) { //清空or返回
        	if(document.getElementById("button2").textContent=="返回"){//两个条件是为了确认发布按钮,修改完成后会调用该方法,
        		window.location.href = './productItems?update='+update + '#activity'
        	}else{
	            this.$refs[formName].resetFields()
	            var uploads = this.$refs.upload;
	            for(var i = 0; i < uploads.length; i++){
	            	uploads[i].clearFiles();
	            }
        	}
        },
        submitForm: function () { //确认发布
        	var _this=this;
        	this.$refs['ruleForm'].validate(function (valid) {
                if (valid) {
		        	$.ajax({
		                url: '/project/saveOrupdateProject',
		                data: {"data":JSON.stringify(_this.ruleForm)},
		                type: 'post',
		                dataType: 'json',
		                success: function (res) {
		                	var update = '';
		                	if(document.getElementById("button2").textContent=="清空"){
		                		_this.$alert('','保存成功', {
		                			confirmButtonText: '确定',
		                			type:'success',
		                			center:'true'
		                		});
		                	}else{
		                		update = 1;
		                	}
		                	_this.resetForm('ruleForm','upload',update);
			            },
		                error: function (err) {
		                	if(err.responseJSON.message=="session clean"){
		                        errorMessage(_this.$message, '登陆已失效重新登陆!');
		                        toLogin();
		                        return;
		                    }
                            if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
		                	_this.$alert('','发布失败，请检查参数或文件是否为空！', {
		                        confirmButtonText: '确定',
			                	type:'error',
			                	center:'true'
			            	});
		                }
		            });
                }
        	});
        },
        /*
         * 页面初始化,加载下拉选项
         * */
        loadOption: function (){
        	var _this = this;

            $.ajax({
                url: '/product/loadOption',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                	_this.relaseState = res.data.releaseState;//发布状态
                	_this.activityFilesTypes = res.data.projectEnclosureCategory;//销售计划附件类别
                 },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                	errorMessage(_this.$message, '初始化下拉列表出错！')
                }
            })
        	var id=UrlParam.param("id");
            var type=UrlParam.param("type");
        	if(id!=null&&id!=""&&type.indexOf("activity")!=-1){
        	//通过id查询对应活动信息
	        	 $.ajax({
	                 url: '/project/findProjectbyId',
	                 data: {"id":id},
	                 type: 'post',
	                 dataType: 'json',
	                 success: function (res) {
	                    _this.ruleForm = res.data;//险种类别
	                 },
	                 error: function (err) {
	                	 if(err.responseJSON.message=="session clean"){
	                         errorMessage(_this.$message, '登陆已失效重新登陆!');
	                         toLogin();
	                         return;
	                     }
	                 	errorMessage(_this.$message, '')
	                 }
	             })
        	}
        }
    }
})
var sale = new Vue({
    el: '#sale',
    data: function () {
        return {
            categories: categories,
            types: types,
            permissionses: permissionses,
            organs: organs,
            filesTypes: productFilesTypes,
            ruleForm: {
                id: '',
                productname: '',
                productcode: '',
                insurancetype: '',
                productstate: '在售',
                releasestate: '有效',
                relaseDate: '',
                ident: '1',
                subproducts: '',
                releasecolumns: [],
                usechannels: [],
                viewablepsns: [],
                viewabledepts: ['分公司'],
                files: [
                        { filesTypes: '建议书', fileList:[]},
                        { filesTypes: '产品彩页', fileList:[]}
                ]
            },
            rules: {
	             /* productcode: [
	                  {required: true, message: '请输入计划代码', trigger: 'blur'},
		              {min: 1, max: 10, message: '请输入长度在 1 到 10 的字符', trigger: 'blur' }
	              ],*/
	              productname: [
	                  {required: true, message: '请输入计划名称', trigger: 'blur'}
	              ],
	          	  insurancetype: [
	          	      {required: true, message: '请选择险种类别', trigger: 'change'}
	              ],
	              productstate: [
	                  {required: true, message: '请选择计划状态', trigger: 'change'}
	              ],
	              releasestate: [
	                  {required: true, message: '请选择发布状态', trigger: 'change'}
	              ],
		          viewabledepts: [
		        	  {required: true, message: '请选择可查看机构', trigger: 'change'}
		          ]
            },
            fileList: [],
            idx: 0,
            products:[]
        }
    },
    created: function () {
    	var parameter = window.location.search
    	if(parameter != null && parameter !=""){
    		document.getElementById("button1").textContent="返回";
    	}
    	this.loadOption()
    },
    methods: {
    	uploadFile: function(index){
    		return "/product/uploadFile/"+index;
    	},
        handlePreview: function () {
            // 点击已上传的文件链接时的钩子，可以通过file.response拿到服务端返回数据
        },
        handleRemove: function (file, fileList) {
            // 文件列表移除文件时的钩子
        	var index = file.index;
        	this.ruleForm.files[index].fileList=fileList;
        },
        beforeRemove: function (file, fileList) {
            // 删除文件之前的钩子，参数为上传的文件和文件列表，若返回false或者返回Promise且被reject，则停止上传。
        	return this.$confirm('确定移除' + file.name)
        },
     // 上传成功后的回调
        uploadSuccess: function(response, file, fileList) {
        	var att = response.data;
        	this.idx = response.data.index;
        	var index = fileList.indexOf(file)
            if (index !== -1) {
            	fileList[index]=att;
            }
        	this.ruleForm.files[this.idx].fileList=fileList;
    
          console.log('上传文件', response)
        },
        // 上传错误
        uploadError: function(response, file, fileList) {
          console.log('上传失败，请重试！')
        },

        handleExceed: function (file, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning('当前限制选择10个文件，本次选择了' + file.length + '个文件，共选择了' + Number(file.length +fileList.length) + '个文件')
        },
        addAccessory: function () { //增加附件
            this.ruleForm.files.push({
                filesTypes: '',
                fileList:[]
            })
        },
        removeAccessory: function (item) { //删除附件
            var index = this.ruleForm.files.indexOf(item)
            if (index !== -1) {
                this.ruleForm.files.splice(index, 1);
//                this.attList.splice(index, 1);
            }
        },
        resetForm: function (formName,upload,update) { //清空or返回
        	if(document.getElementById("button1").textContent=="返回"){
        		window.location.href = './productItems?update='+update + '#sale'
        	}else{
	            this.$refs[formName].resetFields()
	            var uploads = this.$refs.upload;
	            for(var i = 0; i < uploads.length; i++){
	            	uploads[i].clearFiles();
	            }
        	}
        },
        submitForm: function () { //确认发布
        	var _this=this;
        	this.$refs['ruleForm'].validate(function (valid) {
                if (valid) {
		        	$.ajax({
		                url: '/product/saveOrupdateProduct',
		                data: {"data":JSON.stringify(_this.ruleForm)},
		                type: 'post',
		                dataType: 'json',
		                success: function (res) {
		                	var update = ''
		                	if(document.getElementById("button1").textContent=="清空"){
		                		_this.$alert('','保存成功', {
		                			confirmButtonText: '确定',
		                			type:'success',
		                			center:'true'
		                		});
		                	}else{
		                		update = 1;
		                	}
		                	_this.resetForm('ruleForm','upload',update);
		                },
		                error: function (err) {
		                	if(err.responseJSON.message=="session clean"){
		                        errorMessage(_this.$message, '登陆已失效重新登陆!');
		                        toLogin();
		                        return;
		                    }
                            if(err.status == 403){
                                errorMessage(_this.$message, "没有权限，请先申请该权限！");
                                return;
                            }
		                	_this.$alert('','发布失败，请检查参数或文件是否为空！', {
		                        confirmButtonText: '确定',
			                	type:'error',
			                	center:'true'
			            	});
		                }
		            });
                }
            });
        },
        /*
         * 页面初始化,加载下拉选项
         * */
        loadOption: function (){
        	var _this = this;
        	
            $.ajax({
                url: '/product/loadOption',
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    _this.insuranceCategory = res.data.saleInsuranceCategory;//险种类别
                    _this.productState = res.data.productState;//产品状态
                    _this.relaseState = res.data.releaseState;//发布状态
                    _this.types = res.data.releaseColumn;//发布栏目
                    _this.products = res.data.products;//使用产品
                    _this.channels = res.data.useChannels//使用渠道
                    _this.organs = res.data.postOrganization;//可查看岗机构
                    _this.permissionses = res.data.TP_NAME;//可查看岗位
                    _this.saleFilesTypes = res.data.saleEnclosureCategory;//产品组合附件类别
                    var id=UrlParam.param("id");
                    var type=UrlParam.param("type");
                	if(id!=null&&id!=""&&type.indexOf("sale")!=-1){
                	//通过id查询对应产品信息
        	        	 $.ajax({
        	                 url: '/product/findProductbyId',
        	                 data: {"id":id},
        	                 type: 'post',
        	                 dataType: 'json',
        	                 success: function (res) {
        	                    _this.ruleForm = res.data;//险种类别
        	                 },
        	                 error: function (err) {
        	                	 if(err.responseJSON.message=="session clean"){
        	                         errorMessage(_this.$message, '登陆已失效重新登陆!');
        	                         toLogin();
        	                         return;
        	                     }
        	                 	errorMessage(_this.$message, '')
        	                 }
        	             })
                	}
                 },
                error: function (err) {
                	if(err.responseJSON.message=="session clean"){
                        errorMessage(_this.$message, '登陆已失效重新登陆!');
                        toLogin();
                        return;
                    }
                	errorMessage(_this.$message, '初始化下拉列表出错！')
                }
            })
          
        }
    }
})

$(function () {
//    $('.pcoded-left-item').children('li').siblings().removeClass('active pcoded-trigger')
//    $('#4').addClass('active pcoded-trigger')
//    $('#41').addClass('active')
    var type=UrlParam.param("type");
    if (type !== undefined) {
        $('.nav-tabs').children('li').children('a').removeClass('active')
        $('.nav-tabs').children('li').children('a[href="#'+ type +'"]').addClass('active')
        $('.tab-content').children('div').removeClass('active')
        $('#'+type).addClass('active')
    }
    if(type != undefined && type !=""){
    	if(type == 'product'){
    		$("#sales")[0].style.display = 'none'; 
    		$("#activitys")[0].style.display = 'none'; 
    	}
    	if(type == 'sale'){
    		$("#products")[0].style.display = 'none'; 
    		$("#activitys")[0].style.display = 'none'; 
    	}
    	if(type == 'activity'){
    		$("#products")[0].style.display = 'none'; 
    		$("#sales")[0].style.display = 'none'; 
    	}
    }
})